<template>
  <div class="openclass-player">
    <!-- 播放器 -->
    <video
      ref="videoPlayer"
      id="videoPlayer"
      class="video-js"
      disablePictureInPicture
      controlslist="nodownload"
      oncontextmenu="return false;"
    ></video>
  </div>
</template>
<script>
import videojs from "video.js";
import "video.js/dist/video-js.css";
videojs.addLanguage("zh-CN", {
  Play: "播放",
  Pause: "暂停",
  "Current Time": "当前时间",
  Duration: "时长",
  "Remaining Time": "剩余时间",
  "Stream Type": "媒体流类型",
  LIVE: "直播",
  Loaded: "加载完成",
  Progress: "进度",
  Fullscreen: "全屏",
  "Non-Fullscreen": "退出全屏",
  Mute: "静音",
  Unmute: "取消静音",
  "Playback Rate": "播放速度",
  "Play Video": "播放视频",
  Close: "关闭",
});
export default {
  props: {
    videoOptions: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      player: null, // 播放器
      videolength: 0,
      playerOptions: {
        loop: false, // true -- 视频一结束就重新开始
        controls: true,
        autoplay: true, // true--浏览器准备好时开始回放
        height: "360",
        poster: "", // 封面地址
        language: "zh-CN",
        sources: [
          {
            type: "application/x-mpegURL", // 类型
            src: "ccc", // 视频播放路径
          },
        ],
        controlBar: {
          children: [
            { name: "playToggle" }, // 播放按钮
            { name: "currentTimeDisplay" }, // 当前已播放时间
            { name: "progressControl" }, // 播放进度条
            { name: "durationDisplay" }, // 总时间
            {
              name: "volumePanel", // 音量控制
              inline: false, // 不使用水平方式
            },
            { name: "FullscreenToggle" }, // 全屏
          ],
        },
      },
      videoCurrentTime: 0, //实时获取到的视频播放进度，带小数点的毫秒数
      currentVideoUrl: "",
      videoid: this.$route.query.id,
      timeCount: 0, //视频热键计数
      stopTime: 0,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.playerOptions.sources[0].src = this.videoOptions.play_url;
      this.playerOptions.sources[0].type = this.videoOptions.type;
      this.initPlay();
      this.checkResolution();
    });
  },
  watch: {
    currentVideoUrl(newVal, oldVal) {
      if (newVal != oldVal) {
        let vol = this.player && this.player.volume();
        let _now = parseInt(this.player.currentTime());
        let fullscreen = this.player.isFullscreen_;
        if (!this.player.paused()) {
          this.player.pause();
        }
        this.player.src({
          type: "application/x-mpegURL",
          src: this.resolutionOption[newVal],
        });
        setTimeout(() => {
          if (fullscreen) {
            this.player.requestFullscreen();
          }
          this.player.volume(vol);
          this.player.currentTime(_now);
          this.player.play();
        }, 500);
        this.checkResolution(newVal);
      }
    },
  },
  computed: {
    //分辨率
    resolutionOption() {
      let data = {
        "1080P":
          this.videoOptions["1080P"] == "" ? "" : this.videoOptions["1080P"],
        "720P":
          this.videoOptions["720P"] == "" ? "" : this.videoOptions["720P"],
        "480P":
          this.videoOptions["480P"] == "" ? "" : this.videoOptions["480P"],
      };
      return data;
    },
  },
  beforeDestroy() {
    this.player && this.player.dispose();
  },
  methods: {
    // 播放器初始
    initPlay() {
      let self = this;

      this.player = videojs(
        this.$refs.videoPlayer,
        this.playerOptions,
        function onPlayerReady() {
          // 设置键盘热键
          document.onkeydown = (event) => {
            // 当视频标签获取到焦点的时候，热键才有效果
            let act = event.target.playerId;
            if (act === "videoPlayer") {
              event = event || window.event;
              event.preventDefault();
              switch (event.keyCode) {
                // 左-->快退
                case 37:
                  self.timeCount--;
                  break;
                // 右-->快进
                case 39:
                  self.timeCount++;
                  break;
                // 空格-->暂停/播放
                case 32:
                  self.player.paused()
                    ? self.player.play()
                    : self.player.pause();
                  break;
                default:
                  break;
              }
            }
          };
          document.onkeyup = (event) => {
            let act = event.target.playerId;
            if (act === "videoPlayer") {
              event = event || window.event;
              event.preventDefault();
              let _time = 0;
              let _add = self.timeCount > 1 ? 0.2 * self.timeCount : 10;
              let currentTime = self.player.currentTime();
              switch (event.keyCode) {
                // 左-->快退
                case 37:
                  _time = currentTime - _add > 0 ? currentTime - _add : 0;
                  self.player.currentTime(_time);
                  break;
                // 右-->快进
                case 39:
                  _time =
                    currentTime + _add < self.videolength
                      ? currentTime + _add
                      : self.videolength;
                  self.player.currentTime(_time);
                  break;
                default:
                  break;
              }
              self.timeCount = 0;
            }
          };
        }
      );
      this.player.on("play", function () {
        self.onSlicePlay();
      });
      this.player.on("timeupdate", function () {
        self.onPlayerTimeupdate();
      });
      this.player.on("loadedmetadata", function () {
        self.onPlayerLoadeddata();
      });
    },
    // 改变进度条
    onSlicePlay() {
      this.debounce(() => {
        var normal_currentTime = this.player.currentTime();
        var unnormal_currentTime = this.player.currentTime();
        if (normal_currentTime.toString() == unnormal_currentTime.toString()) {
          this.player.pause();
          this.player.play();
        }
      }, 100);
    },
    //延迟处理
    debounce(func, wait, immediate) {
      let timeout, args, context, timestamp, result;
      const later = function () {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp;

        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
        if (last < wait && last > 0) {
          timeout = setTimeout(later, wait - last);
        } else {
          timeout = null;
          // 如果设定为immediate===true，因为开始已经调用过了此处无需调用
          if (!immediate) {
            result = func.apply(context, args);
            if (!timeout) context = args = null;
          }
        }
      };
      return function (...args) {
        context = this;
        timestamp = +new Date();
        const callNow = immediate && !timeout;
        // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait);
        if (callNow) {
          result = func.apply(context, args);
          context = args = null;
        }

        return result;
      };
    },
    //实时获取视频播放的信息
    onPlayerTimeupdate() {
      //实时获取当前的播放进度时间（毫秒数，带小数点）
      this.videoCurrentTime = this.player.currentTime();
      //如果个人中心或者后台设置了暂停的间隔时间功能：
      if (this.videoOptions.stop_time > 0) {
        let _currentTime = this.player.currentTime(); //当前播放进度的秒数
        let _stop = this.videoOptions.stop_time * 60; //隔多少秒暂停
        // 如果整除就暂停
        if (parseInt(_currentTime) > 0 && parseInt(_currentTime) % _stop == 0) {
          if (this.stopTime == 0 || _currentTime - this.stopTime > 1) {
            this.player.pause();
          }
          this.stopTime = _currentTime;
        }
      }
    },
    // 视频加载完毕装备就绪
    onPlayerLoadeddata() {
      this.videolength = this.player.duration(); //获取视频的长度
    },
    checkResolution(isChange) {
      let self = this;
      if (!document.querySelector(".transcoding")) {
        let playerBar = document.querySelector(".vjs-control-bar"),
          fullScreen = document.querySelector(
            ".vjs-fullscreen-control.vjs-control.vjs-button"
          ),
          div = document.createElement("div"),
          dl = document.createElement("dl"),
          arr = this.resolutionOption,
          dt = document.createElement("dt");

        div.className = "transcoding";
        if (arr["1080P"]) {
          let dd = document.createElement("dd");
          dd.innerText = "1080P";
          dl.appendChild(dd);
        }

        if (arr["720P"]) {
          let dd = document.createElement("dd");
          dd.innerText = "720P";
          dl.appendChild(dd);
        }

        if (arr["480P"]) {
          let dd = document.createElement("dd");
          dd.innerText = "480P";
          dl.appendChild(dd);
        }

        if (dl.children.length) {
          dt.className = "acitve";
          dt.innerText = isChange ? isChange : dl.children[0].innerText;
          dl.appendChild(dt);
          div.appendChild(dl);
          playerBar.insertBefore(div, fullScreen);
        }
        let dlChildren = [...dl.children].slice(0, -1);
        function changeUrl1(e) {
          if (dt.innerText == e.target.innerText) {
            return;
          }
          dt.innerText = e.target.innerText;
          self.currentVideoUrl = e.target.innerText;
        }
        for (let i = 0; i < dlChildren.length; i++) {
          dlChildren[i].addEventListener("click", changeUrl1, true);
        }
      }
    },
  },
};
</script>
<style lang="scss">
.openclass-player {
  height: 100%;
  .video-js {
    width: 100%;
    height: 100%;
    .vjs-big-play-button {
      top: calc(50% - 42px);
      left: 50%;
    }
  }
  .strailtip {
    margin-top: 30vh;
  }
}
</style>
